import 'package:pinyin/pinyin.dart';

class AllAlbum {
  static final AllAlbum _instance = AllAlbum._internal();
  List<AlbumList> albumList;
  // 私有构造函数
  AllAlbum._internal({List<AlbumList>? albums}) : albumList = albums ?? [];
  // 工厂构造函数返回单例实例
  factory AllAlbum() => _instance;
  // 静态方法获取实例
  static AllAlbum get instance => _instance;
  void addAlbum(AlbumList album) {
    albumList.add(album);
  }
  void removeAlbum(String albumName) {
    albumList.removeWhere((album) => album.albumName == albumName);
  }
  AlbumList? findAlbumByName(String name) {
    try {
      return albumList.firstWhere((album) => album.albumName == name);
    } catch (e) {
      return null;
    }
  }
  void sortAlbumsByName() {
    albumList.sort((a, b) {
      String pinyinA = PinyinHelper.getPinyin(
          a.albumName,
          separator: '',
          format: PinyinFormat.WITHOUT_TONE
      );
      String pinyinB = PinyinHelper.getPinyin(
          b.albumName,
          separator: '',
          format: PinyinFormat.WITHOUT_TONE
      );
      return pinyinA.compareTo(pinyinB);
    });
  }

  bool containsAlbum(String name) {
    return albumList.any((album) => album.albumName == name);
  }
  void printAllAlbum() {
    albumList.forEach((album) {
      album.printMusicList();
    });
  }
}



class AlbumList {
  String albumName;
  String albumCover;
  List<MusicList> musicList;

  AlbumList({
    required this.albumName,
    required this.albumCover,
    required this.musicList,
  });

  void addMusic(MusicList music) {
    musicList.add(music);
  }

  void removeMusic(String musicName) {
    musicList.removeWhere((music) => music.musicName == musicName);
  }

  MusicList? findMusicByName(String name) {
    try {
      return musicList.firstWhere((music) => music.musicName == name);
    } catch (e) {
      return null;
    }
  }

  void sortMusicByName() {
    musicList.sort((a, b) => a.musicName.compareTo(b.musicName));
  }

  void printMusicList() {
    print("albumName: $albumName, albumCover: $albumCover");
    musicList.forEach((music) {
      music.printMusicList();
    });
  }
}

class MusicList {
  String musicName;
  String musicAuthor;
  String musicPath;

  MusicList({
    required this.musicName,
    required this.musicAuthor,
    required this.musicPath
  });

  void printMusicList() {
    print("musicName: $musicName, musicAuthor: $musicAuthor, musicPath: $musicPath");
  }
}